package com.example.dict.ativities;


import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ExpandableListView;
import android.widget.GridView;
import android.widget.TextView;

import com.example.dict.R;
import com.example.dict.adapter.SearchLeftAdapter;
import com.example.dict.adapter.SearchRightAdapter;
import com.example.dict.bean.pinbuBean;
import com.example.dict.bean.pinbuWordBean;
import com.example.dict.db.DBManager;
import com.example.dict.utils.ApiUtil;
import com.example.dict.utils.AssetsUtil;
import com.example.dict.utils.CommonUtil;
import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshGridView;

import java.util.ArrayList;
import java.util.List;

public class BaseSearchActivity extends BaseActivity {


    ExpandableListView mExpandableListView;
    PullToRefreshGridView mPullToRefreshGridView;
    TextView mTitleTv;
    List<String> groupDatas;//外层分组列表{A,B,C,D....}
    List<List<pinbuBean.ResultBean>> childDatas;
    SearchLeftAdapter mLeftEVAdapter;
    SearchRightAdapter mRightGVAdapter;
    int selGroupPos = 0;//被点击的组的位置
    int selChildPos = 0;//选中组中的某一个位置

    List<pinbuWordBean.ResultBean.ListBean> GridDatas;//右侧GridView的数据源，先声明

    int totalPage;//总页数
    int Page;//获取的页数
    int PageSize = 48;//默认一页获取48个
    String Word = "";//点击了左边的哪个拼音或部首
    String Url = "";
    Intent intent;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_query_pinyin);


        mExpandableListView = findViewById(R.id.searchpy_elv);
        mPullToRefreshGridView = findViewById(R.id.searchpy_gv);
        mTitleTv = findViewById(R.id.searchpy);


        //初始化GridView数据源内容
        initGridDatas();


    }

    /**
     * 初始化GridView数据源内容
     */
    private void initGridDatas() {
        GridDatas = new ArrayList<>();
        //设置适配器
        mRightGVAdapter = new SearchRightAdapter(this,GridDatas);
        mPullToRefreshGridView.setAdapter(mRightGVAdapter);

    }
    //设置GridView的监听器
    public void setGVListener(final int type) {
        //上拉加载的监听器
        mPullToRefreshGridView.setMode(PullToRefreshBase.Mode.PULL_FROM_END);//上拉刷新
        mPullToRefreshGridView.setScrollingWhileRefreshingEnabled(true);//刷新时允许滑动
        mPullToRefreshGridView.getLoadingLayoutProxy(false,true).setPullLabel("上拉加载");
        mPullToRefreshGridView.getLoadingLayoutProxy(false,true).setRefreshingLabel("正在加载");
        mPullToRefreshGridView.getLoadingLayoutProxy(false,true).setReleaseLabel("放开以加载");
        mPullToRefreshGridView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<GridView>() {
            @Override
            public void onRefresh(PullToRefreshBase<GridView> refreshView) {
//                判断当前加载的页数是否小于总页数
                if (Page <totalPage){
                    Page++;
                    if (type == CommonUtil.TYPE_PINYIN){
                        Url = ApiUtil.getPinyinurl(Word,Page,PageSize);
                    }else if (type == CommonUtil.TYPE_BUSHOU){
                        Url = ApiUtil.getBushouurl(Word,Page,PageSize);
                    }
                    loadData(Url);
                }else {
                    mPullToRefreshGridView.onRefreshComplete();//不用加载了

                }

            }
        });
        //点击每一项，能够跳转到详情页面的监听
        mPullToRefreshGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //跳转到文字查询详情页面
                pinbuWordBean.ResultBean.ListBean bean = GridDatas.get(position);
                String zi = bean.getZi();
                 intent = new Intent(getBaseContext(), WordInfoActivity.class);
                 intent.putExtra("zi",zi);
                startActivity(intent);

            }
        });
    }


    /**
     * 加载数据成功时会调用的方法，因为json格式数据相同，解析到相同的集合里
     * 所有就将代码提取到父类当中编写，避免代码冗余
     */
    @Override
    public void onSuccess(String result) {
        Gson gson = new Gson();
        pinbuWordBean bean = gson.fromJson(result, pinbuWordBean.class);
        pinbuWordBean.ResultBean resultBean = bean.getResult();
        totalPage = resultBean.getTotalpage();//获取数据的总页数进行保存
        List<pinbuWordBean.ResultBean.ListBean> list = resultBean.getList();
        //将数据进行加载
        refreshDataByGv(list);
        //将加载到的网络数据写入到数据库当中
        writeDBByThread(list);
    }

    /**
     * 将网络数据保存到数据库当中,
     * @param list
     */
    private void writeDBByThread(final List<pinbuWordBean.ResultBean.ListBean> list) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                DBManager.insertListToPyWord(list);
            }
        }).start();
    }



    /**
     * 更新GridView数据，显示适配器要重新加载
     * @param list
     */
    public void refreshDataByGv(List<pinbuWordBean.ResultBean.ListBean> list) {
        if (Page == 1){//加载了新的拼音或者部首的集合
            GridDatas.clear();
            GridDatas.addAll(list);
            mRightGVAdapter.notifyDataSetChanged();
        }else {//进行上拉加载新的的一页，保留原来的数据
            GridDatas.addAll(list);
            mRightGVAdapter.notifyDataSetChanged();
            //停止显示加载条
            mPullToRefreshGridView.onRefreshComplete();
        }
    }


    /**
     * 设置expandableListView的监听事件
     */
    public void setExLvListenr(final int type) {
        mExpandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
                mLeftEVAdapter.setSelectGroupPos(groupPosition);

                selGroupPos = groupPosition;
                int groupSize = childDatas.get(selGroupPos).size();
                if (groupSize <=selChildPos){
                    selChildPos = groupSize-1;
                    mLeftEVAdapter.setSelectChildPos(selChildPos);
                }
                mLeftEVAdapter.notifyDataSetInvalidated();//数据没有改变，只是布局背景改变了
                //获取数据信息
                getDataIterWord(type);
                return false;
            }
        });
        mExpandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
                mLeftEVAdapter.setSelectGroupPos(groupPosition);
                mLeftEVAdapter.setSelectChildPos(childPosition);
                mLeftEVAdapter.notifyDataSetInvalidated();
                selGroupPos = groupPosition;
                selChildPos = childPosition;
                //网络加载右边Grid加载的内容
                getDataIterWord(type);

                return false;
            }
        });
    }


    /**
     * 改变了左边的选中的拼音或部首，从网上获取对应选中的结果，显示在右边
     */
    private void getDataIterWord(int type) {
        List<pinbuBean.ResultBean> groupList = childDatas.get(selGroupPos);//获取选中组

            Page = 1;//新的一页，
            pinbuBean.ResultBean be = groupList.get(selChildPos);
            if (type == CommonUtil.TYPE_PINYIN){
                Word = be.getPinyin();
                Url = ApiUtil.getPinyinurl(Word,Page,PageSize);
            }else if (type == CommonUtil.TYPE_BUSHOU){
                Word = be.getBushou();
                Url = ApiUtil.getBushouurl(Word,Page,PageSize);
            }
            loadData(Url);

    }


    public void initData(String assetName,int type) {
        /**
         *读取assets文件夹的数据，使用Gson解析，将数据分级存储在二维列表中
         * assetName 文件名称
         * type 文件类型 pinyin--0 ，bushou --1
         */
        groupDatas = new ArrayList<>();
        childDatas = new ArrayList<>();
        String json = AssetsUtil.getAssetsContent(this, assetName);//获得json数据
        if (!TextUtils.isEmpty(json)){
            Gson gson = new Gson();
            pinbuBean pinbubean = gson.fromJson(json, pinbuBean.class);
            List<pinbuBean.ResultBean> resultlist = pinbubean.getResult();
            //整理数据
            List<pinbuBean.ResultBean> grouplist = new ArrayList<>();//声明每组包含的元素集合
            for(int i = 0; i<resultlist.size();i++){
                pinbuBean.ResultBean bean = resultlist.get(i);
                if (type == CommonUtil.TYPE_PINYIN){
                    String pinyin_key = bean.getPinyin_key();//获取大写字母（A,B,C...）
                    if (!groupDatas.contains(pinyin_key)) { //判断大写字母是否存在于分组列表中
                        groupDatas.add(pinyin_key);
                        if (grouplist.size()>0){
                            childDatas.add(grouplist);
                        }
                        grouplist = new ArrayList<>();
                        grouplist.add(bean);
                    }else {
                        grouplist.add(bean);//大写字母存在，表明还在当前这组中，可以直接添加
                    }

                }else if (type == CommonUtil.TYPE_BUSHOU){
                    String bihua = bean.getBihua();
                    if (!groupDatas.contains(bihua)) {
                        groupDatas.add(bihua);
                        if (grouplist.size()>0){
                            childDatas.add(grouplist);
                        }
                        grouplist = new ArrayList<>();
                        grouplist.add(bean);

                    }else {
                        grouplist.add(bean);//当前bihua存在，不用向组当中添加
                    }

                }
            }
//            循环结束之后，最后一组没有添加进去，需要手动添加
            childDatas.add(grouplist);
            mLeftEVAdapter = new SearchLeftAdapter(this, groupDatas, childDatas, type);
            mExpandableListView.setAdapter(mLeftEVAdapter);
        }
    }

    /**
     * 头部布局返回键
     * @param view
     */
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.searchpy_back:
                finish();
                break;
        }
    }

}
